﻿
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditor.AddressableAssets.Settings;



public class AddressableProcessGroupFolder : Editor
{
    static Dictionary<string, int> addressDics = new Dictionary<string, int>();
    static AddressableAssetSettings assetSettings => AddressableBuildTools.assetSettings;
    static List<AddressableAssetGroupSchema> newSchemas => new List<AddressableAssetGroupSchema> { assetSettings.DefaultGroup.Schemas[0], assetSettings.DefaultGroup.Schemas[1] };


    [MenuItem("Assets/Lr/Addressable/AdaptGroupFolder")]
    public static void AutoAdaptGroupFolder()
    {
        if (!Directory.Exists(AddressableBuildTools.AddressableAssetsPath))
        {
            Debug.LogError("AddressableAssets文件夹尚未创建，请先 右键=>选择Addressable/Creat/Init_Folder");
            return;
        }

        addressDics.Clear();
        DirectoryInfo info = new DirectoryInfo(AddressableBuildTools.AddressableAssetsPath);
        foreach (var item in info.GetDirectories())
        {
            if (AddressableFolderEditor.baseTypeGroups.Contains(item.Name))
            {
                ProcessGroups(new ResFolder(item));
            }
        }

       var  isOn = EditorUtility.DisplayDialog("自动生成key","是否自动生成 addressable Entry 对应的 cs脚本常量","是","否");
        if (isOn)
        {
            AddressableCreatEditor.CreatAddFolder();
        }
    }

    static void ProcessGroups(ResFolder folder)
    {
        foreach (var groupSinle in folder.resGroups)
        {
            var assetGroup = assetSettings.FindGroup(groupSinle.name);
            if (assetGroup == null)
            {
                assetGroup = assetSettings.CreateGroup(groupSinle.name, false, false, true, newSchemas);
            }

            ProcessEntry(groupSinle, assetGroup);
        }
    }

    static void ProcessEntry(AddressableResGroup groupSinle, AddressableAssetGroup assetGroup)
    {
        foreach (var file in groupSinle.resFiles)
        {
            var entry = assetGroup.GetAssetEntry(file.addressHash);
            if (entry == null)
            {
                entry = assetSettings.CreateOrMoveEntry(file.addressHash, assetGroup, false, true);
            }

            if (addressDics.TryGetValue(file.address, out int count))
            {
                entry.address = $"{file.address}({count})";
                addressDics[file.address] = ++count;
            }
            else
            {
                entry.address = file.address;
                addressDics.Add(file.address, 1);
            }

            ProcessEntryLabel(file, entry);
        }
    }

    static void ProcessEntryLabel(AddressableResFile file, AddressableAssetEntry entry)
    {
        foreach (var label in file.addressLabel)
        {
            if (!assetSettings.GetLabels().Contains(label))
            {
                assetSettings.AddLabel(label);
            }
            entry.SetLabel(label, true);
        }
    }


    [MenuItem("Assets/Lr/Addressable/ReplaceGroupFolder")]
    public static void ReplaceUpdateContentEntry()
    {

        List<AddressableAssetGroup> updates = new List<AddressableAssetGroup>();
        Dictionary<string, List<AddressableAssetEntry>> tempGroups = new Dictionary<string, List<AddressableAssetEntry>>();

        foreach (var item in assetSettings.groups)
        {
            if (item.name.Contains(AddressableBuildTools.UpdateTag))
            {
                updates.Add(item);
            }
        }

        foreach (var item in updates)
        {
            foreach (var entry in item.entries)
            {
                if (!entry.AssetPath.Contains(AddressableBuildTools.ShortAddressableAssetsPath))
                {
                    continue;
                }

                var paths = entry.AssetPath
                    .Replace($"{AddressableBuildTools.ShortAddressableAssetsPath}/", "")
                    .Replace('\\', '/')
                    .Split('/');

                var groupName = $"{paths[0]}_{paths[1]}".Replace(AddressableBuildTools.GroupTag,"");

                if (tempGroups.TryGetValue(groupName, out List<AddressableAssetEntry> assetEntries))
                {
                    assetEntries.Add(entry);
                }
                else
                {
                    Debug.Log(groupName);
                    assetEntries = new List<AddressableAssetEntry>();
                    assetEntries.Add(entry);
                    tempGroups[groupName] = assetEntries;
                }
            }
        }

        foreach (var item in tempGroups)
        {
            var group = assetSettings.FindGroup(item.Key);
            assetSettings.MoveEntries(item.Value, group);
        }


        foreach (var item in updates)
        {
            if (item.entries.Count <= 0)
            {
                assetSettings.RemoveGroup(item);
            }
        }
    }
}
